"use client"

import { useState, useEffect } from 'react'
import { SimpleEvolutionTimeline } from '../SimpleEvolutionTimeline'
import { textStyles, fontSizes, fontWeights } from '../../lib/fontConfig'
// 教学提醒组件已移除
import { useProgressManager } from '../../lib/progressManager'

interface Course {
  lesson_number: string
  course_name: string
  target_char: string
}

interface RadicalStrokeDisplayProps {
  currentCourse?: Course
  selectedRadical: string
}

interface RadicalInfo {
  id: string
  character: string
  name: string
  pronunciation: string
  strokeCount: number
  origin: string
  meaning: string
  examples: string[]
  evolutionSteps: string[]
  position: string // 部首位置：左、右、上、下、包围等
  category: 'radical' | 'stroke' // 区分是部首还是笔画
}

export function RadicalStrokeDisplay({ currentCourse, selectedRadical }: RadicalStrokeDisplayProps) {
  const [selectedTab, setSelectedTab] = useState('overview')
  const [radicalInfo, setRadicalInfo] = useState<RadicalInfo | null>(null)
  const [isPlaying, setIsPlaying] = useState(false)
  const [allRadicals, setAllRadicals] = useState<string[]>([])
  
  const { 
    isRadicalLearned, 
    getRadicalProgress,
    generateSmartContent 
  } = useProgressManager()

  // 根据当前汉字和选中的部首获取详细信息
  useEffect(() => {
    if (currentCourse?.target_char) {
      const database = getRadicalDatabase()
      const charData = database[currentCourse.target_char as keyof typeof database]
      
      if (charData) {
        const radicals = Object.keys(charData)
        setAllRadicals(radicals)
        
        // 如果selectedRadical是默认值'bushou'或者找不到对应信息，则使用第一个部首
        let targetRadical = selectedRadical
        if (selectedRadical === 'bushou' || !getRadicalInfo(currentCourse.target_char, selectedRadical)) {
          targetRadical = radicals[0] // 使用第一个部首
        }
        
        const info = getRadicalInfo(currentCourse.target_char, targetRadical)
        setRadicalInfo(info)
      }
    }
  }, [selectedRadical, currentCourse])

  // 获取部首数据库
  const getRadicalDatabase = () => {
    return {
      '木': {
        '木': {
          id: 'mu',
          character: '木',
          name: '木字旁',
          pronunciation: 'mù',
          strokeCount: 4,
          origin: '象形字，像一棵树的形状，有根、干、枝',
          meaning: '树木、植物、木材的总称，引申为朴实、自然',
          examples: ['林', '森', '桌', '椅', '树', '枝'],
          evolutionSteps: ['🌳', '𣎳', '木'],
          position: '左旁、独体',
          category: 'radical'
        },
        '一': {
          id: 'yi',
          character: '一',
          name: '横',
          pronunciation: 'yī',
          strokeCount: 1,
          origin: '指事字，一条横线表示数字"一"',
          meaning: '数字一，表示单一、开始、统一',
          examples: ['二', '三', '上', '下', '不', '正'],
          evolutionSteps: ['—', '一'],
          position: '独体、上部',
          category: 'stroke'
        },
        '丨': {
          id: 'shu',
          character: '丨',
          name: '竖',
          pronunciation: 'shù',
          strokeCount: 1,
          origin: '指事字，一条竖线表示垂直方向',
          meaning: '垂直、正直、中央',
          examples: ['中', '申', '甲', '由'],
          evolutionSteps: ['|', '丨'],
          position: '中央、独体',
          category: 'stroke'
        },
        '丿': {
          id: 'pie',
          character: '丿',
          name: '撇',
          pronunciation: 'piě',
          strokeCount: 1,
          origin: '指事字，向左下倾斜的笔画',
          meaning: '倾斜、分离、向外',
          examples: ['人', '入', '八', '分'],
          evolutionSteps: ['/', '丿'],
          position: '左上、独体',
          category: 'stroke'
        },
        '丶': {
          id: 'dian',
          character: '丶',
          name: '点',
          pronunciation: 'diǎn',
          strokeCount: 1,
          origin: '指事字，一个小点表示位置或装饰',
          meaning: '小、精确、装饰',
          examples: ['主', '丹', '为', '义'],
          evolutionSteps: ['•', '丶'],
          position: '上部、右上',
          category: 'stroke'
        }
      },
      '水': {
        '氵': {
          id: 'shui',
          character: '氵',
          name: '三点水',
          pronunciation: 'shuǐ',
          strokeCount: 3,
          origin: '由"水"字简化而来，三点表示水滴',
          meaning: '与水相关的事物',
          examples: ['河', '湖', '海', '洗', '清', '流'],
          evolutionSteps: ['水', '氵'],
          position: '左旁',
          category: 'radical'
        },
        '水': {
          id: 'shui_full',
          character: '水',
          name: '水字旁',
          pronunciation: 'shuǐ',
          strokeCount: 4,
          origin: '象形字，像水流的样子',
          meaning: '液体、流动、清洁',
          examples: ['水果', '水面', '水滴'],
          evolutionSteps: ['🌊', '氺', '水'],
          position: '独体、下部',
          category: 'radical'
        }
      }
    }
  }

  // 获取部首笔画信息
  const getRadicalInfo = (baseChar: string, radical: string): RadicalInfo | null => {
    const database = getRadicalDatabase()
    const charData = database[baseChar as keyof typeof database]
    if (!charData) return null
    return (charData as any)[radical] || null
  }

  // 发音功能（后续可集成大模型）
  const playPronunciation = async () => {
    if (!radicalInfo || isPlaying) return
    
    setIsPlaying(true)
    
    try {
      // TODO: 后续集成大模型发音
      // const audioUrl = await generateAudioFromLLM(radicalInfo.character, radicalInfo.pronunciation)
      // const audio = new Audio(audioUrl)
      // await audio.play()
      
      // 临时模拟发音效果
      console.log(`发音: ${radicalInfo.character} - ${radicalInfo.pronunciation}`)
      
      // 模拟发音时长
      setTimeout(() => {
        setIsPlaying(false)
      }, 1500)
      
    } catch (error) {
      console.error('发音失败:', error)
      setIsPlaying(false)
    }
  }

  const tabs = [
    { id: 'overview', label: '概览', icon: '📋' },
    { id: 'pronunciation', label: '读音', icon: '🔊' },
    { id: 'strokes', label: '笔画', icon: '✏️' },
    { id: 'origin', label: '起源', icon: '🏛️' },
    { id: 'meaning', label: '含义', icon: '💭' }
  ]

  if (!radicalInfo) {
    return (
      <div className="h-full flex items-center justify-center bg-gradient-to-br from-green-50 via-blue-50 to-purple-50">
        <div className="text-center">
          <div className="text-6xl mb-4">📝</div>
          <h3 className="text-xl font-bold text-gray-700 mb-2">选择一个部首或笔画</h3>
          <p className="text-gray-500">点击下方的部首笔画开始学习</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col bg-gradient-to-br from-green-50 via-blue-50 to-purple-50">
      {/* 标题区域 */}
      <div className="bg-white/90 backdrop-blur-sm rounded-t-2xl p-4 border-b border-green-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <div className={`w-16 h-16 bg-gradient-to-br from-green-500 to-blue-500 rounded-xl flex items-center justify-center text-white ${fontSizes.heading.lg} ${fontWeights.bold}`}>
              {radicalInfo.character}
            </div>
            <div>
              <h2 className={`${textStyles.mainTitle} text-gray-800`}>{radicalInfo.name}</h2>
              <div className={`flex items-center space-x-4 ${textStyles.caption} text-gray-600`}>
                <span>读音：{radicalInfo.pronunciation}</span>
                <span>笔画：{radicalInfo.strokeCount}画</span>
                <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                  radicalInfo.category === 'radical' 
                    ? 'bg-green-100 text-green-700' 
                    : 'bg-blue-100 text-blue-700'
                }`}>
                  {radicalInfo.category === 'radical' ? '部首' : '笔画'}
                </span>
              </div>
            </div>
          </div>
          <div className="text-2xl">
            {radicalInfo.category === 'radical' ? '🏗️' : '✏️'}
          </div>
        </div>
      </div>

      {/* Tab导航 */}
      <div className="bg-white/70 backdrop-blur-sm p-2">
        <div className="flex space-x-1 overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setSelectedTab(tab.id)}
              className={`
                flex items-center space-x-2 py-2 px-4 rounded-lg transition-all duration-300 whitespace-nowrap
                ${selectedTab === tab.id
                  ? 'bg-gradient-to-r from-green-500 to-blue-500 text-white shadow-lg'
                  : 'bg-white/50 text-gray-700 hover:bg-white/80'
                }
              `}
            >
              <span className={fontSizes.body.md}>{tab.icon}</span>
              <span className={`${fontSizes.body.md} ${fontWeights.medium}`}>{tab.label}</span>
            </button>
          ))}
        </div>
      </div>

      {/* 内容区域 */}
      <div className="flex-1 p-3 overflow-hidden">
        {selectedTab === 'overview' && (
          <div className="h-full flex flex-col space-y-3">
            <div className="bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-green-100">
              <h3 className={`${textStyles.sectionTitle} text-gray-800 mb-3 flex items-center`}>
                <span className="mr-2">📋</span>
                基本信息
              </h3>
              <div className="grid grid-cols-2 gap-3">
                <div className="bg-green-50 rounded-lg p-3">
                  <div className={`${textStyles.caption} text-green-600`}>名称</div>
                  <div className={`${textStyles.subTitle} text-green-800`}>{radicalInfo.name}</div>
                </div>
                <div className="bg-blue-50 rounded-lg p-3">
                  <div className={`${textStyles.caption} text-blue-600`}>读音</div>
                  <div className={`${textStyles.subTitle} text-blue-800`}>{radicalInfo.pronunciation}</div>
                </div>
                <div className="bg-purple-50 rounded-lg p-3">
                  <div className={`${textStyles.caption} text-purple-600`}>笔画数</div>
                  <div className={`${textStyles.subTitle} text-purple-800`}>{radicalInfo.strokeCount}画</div>
                </div>
                <div className="bg-orange-50 rounded-lg p-3">
                  <div className={`${textStyles.caption} text-orange-600`}>位置</div>
                  <div className={`${textStyles.subTitle} text-orange-800`}>{radicalInfo.position}</div>
                </div>
              </div>
            </div>

            <div className="flex-1 bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-blue-100">
              <h3 className="text-lg font-bold text-gray-800 mb-3 flex items-center">
                <span className="mr-2">🎯</span>
                核心含义
              </h3>
              <p className="text-gray-700 leading-relaxed">{radicalInfo.meaning}</p>
            </div>
          </div>
        )}

        {selectedTab === 'pronunciation' && (
          <div className="h-full flex items-center justify-center">
            <div className="bg-white/90 backdrop-blur-sm rounded-xl p-6 shadow-lg border border-green-100 text-center max-w-md w-full">
              <h3 className="text-lg font-bold text-gray-800 mb-4 flex items-center justify-center">
                <span className="mr-2">🔊</span>
                读音练习
              </h3>
              <div className="mb-6">
                <div className={`${textStyles.primaryCharacter} text-green-600 mb-3`}>{radicalInfo.character}</div>
                <div className={`${fontSizes.display.md} ${fontWeights.bold} text-blue-600 mb-2`}>{radicalInfo.pronunciation}</div>
                <div className={`${textStyles.sectionTitle} text-gray-600`}>{radicalInfo.name}</div>
              </div>
              <button 
                onClick={playPronunciation}
                disabled={isPlaying}
                className={`
                  ${textStyles.primaryButton} py-3 px-6 rounded-xl transform transition-all duration-300 shadow-lg relative overflow-hidden
                  ${isPlaying 
                    ? 'bg-gradient-to-r from-orange-500 to-red-500 text-white cursor-not-allowed'
                    : 'bg-gradient-to-r from-green-500 to-blue-500 text-white hover:from-green-600 hover:to-blue-600 hover:scale-105'
                  }
                `}
              >
                {/* 播放时的波纹效果 */}
                {isPlaying && (
                  <div className="absolute inset-0 bg-white opacity-20 animate-ping rounded-xl"></div>
                )}
                
                <span className="relative z-10">
                  {isPlaying ? '🔊 播放中...' : '🔊 点击发音'}
                </span>
              </button>
            </div>
          </div>
        )}

        {selectedTab === 'strokes' && (
          <div className="h-full flex flex-col">
            <div className="bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-blue-100 h-full flex flex-col">
              <h3 className="text-lg font-bold text-gray-800 mb-3 flex items-center">
                <span className="mr-2">✏️</span>
                笔画分析
              </h3>
              <div className="text-center mb-4">
                <div className="text-6xl font-bold text-blue-600 mb-2">{radicalInfo.character}</div>
                <div className="text-lg font-bold text-gray-700">共 {radicalInfo.strokeCount} 画</div>
              </div>
              
              <div className="flex-1 bg-blue-50 rounded-xl p-3">
                <h4 className="font-bold text-blue-800 mb-2">笔画顺序</h4>
                <div className="grid grid-cols-4 gap-2">
                  {[...Array(radicalInfo.strokeCount)].map((_, i) => (
                    <div key={i} className="bg-white rounded-lg p-2 text-center border-2 border-blue-200">
                      <div className="text-xs text-blue-600 font-medium">第{i+1}画</div>
                      <div className="text-xl font-bold text-blue-800">{radicalInfo.character}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {selectedTab === 'origin' && (
          <div className="h-full flex flex-col space-y-3">
            <div className="bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-purple-100">
              <h3 className="text-lg font-bold text-gray-800 mb-3 flex items-center">
                <span className="mr-2">🏛️</span>
                字形起源
              </h3>
              <div className="bg-purple-50 rounded-xl p-4">
                <p className="text-gray-700 leading-relaxed">{radicalInfo.origin}</p>
              </div>
            </div>
            
            <div className="flex-1 bg-gradient-to-r from-purple-100 to-pink-100 rounded-xl p-4">
              <h4 className="font-bold text-purple-800 mb-3">演变过程</h4>
              <div className="h-full">
                <SimpleEvolutionTimeline 
                  title={`${radicalInfo.character}字演变过程`}
                  steps={radicalInfo.evolutionSteps.map((step, index) => ({
                    character: step,
                    period: index === 0 ? '甲骨文时期' : index === radicalInfo.evolutionSteps.length - 1 ? '现代汉字' : '金文时期',
                    description: index === 0 
                      ? `这是${radicalInfo.character}字最早的形态，刻在龟甲和兽骨上` 
                      : index === radicalInfo.evolutionSteps.length - 1 
                        ? `这是我们现在使用的${radicalInfo.character}字，经过了几千年的演变`
                        : `这是${radicalInfo.character}字在青铜器时代的写法，比甲骨文更规整`
                  }))}
                />
              </div>
            </div>
          </div>
        )}

        {selectedTab === 'meaning' && (
          <div className="h-full flex items-center justify-center">
            <div className="bg-white/90 backdrop-blur-sm rounded-xl p-6 shadow-lg border border-orange-100 max-w-2xl w-full">
              <h3 className="text-lg font-bold text-gray-800 mb-4 flex items-center">
                <span className="mr-2">💭</span>
                深层含义
              </h3>
              <div className="bg-orange-50 rounded-xl p-5">
                <p className="text-gray-700 leading-relaxed text-lg mb-4">{radicalInfo.meaning}</p>
                
                <div className="border-t border-orange-200 pt-4">
                  <h4 className="font-bold text-orange-800 mb-2">文化内涵</h4>
                  <p className="text-orange-700">
                    {radicalInfo.category === 'radical' 
                      ? `作为部首，"${radicalInfo.character}"常用来构成与${radicalInfo.meaning}相关的汉字，体现了汉字造字的规律性。`
                      : `作为基本笔画，"${radicalInfo.character}"是构成汉字的基础元素，体现了汉字的结构美。`
                    }
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}

        
      </div>

      {/* 教学提醒组件已移除 */}
    </div>
  )
} 